//
//  HNSalesManCycleDetailView.m
//  优学荟管理系统
//
//  Created by edz on 2017/11/6.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNSalesManCycleDetailView.h"
#import <PNChart.h>
#import <HcdDateTimePickerView.h>
#import "HNSalesManCycleDetailDateView.h"
#import "HNSalesManCyleDetailCategoryView.h"

@implementation HNSalesManCycleDetailView
{
    __weak IBOutlet UIView *_CycleView;
    PNPieChart *_PieChart;
    
    // 名称
    __weak IBOutlet UILabel *_Title;
    // 负责人
    __weak IBOutlet UILabel *_Name;
    // 开始时间
    __weak IBOutlet UIButton *_BeginTimeBtn;
    // 结束时间
    __weak IBOutlet UIButton *_EndTimeBtn;
    // 评价次数
    __weak IBOutlet UILabel *_CommentCount;
    // 查看次数
    __weak IBOutlet UILabel *_SeeCount;
    // 得优排序的View
    __weak IBOutlet UIScrollView *_CategoryScrollView;
    
    __weak IBOutlet UILabel *_UnitLabel;//业务总提成
    
    //缴费评价项
    __weak IBOutlet UILabel *_PayEvaluateLabel;//缴费评价
    __weak IBOutlet UILabel *_AllEvaluateTimeLabel;//评价总次数
    __weak IBOutlet UILabel *_UseEvaluateTimeLabel;//有效评价总次数;
    __weak IBOutlet UILabel *_SeeAllTimeLabel;//查看总次数;
    
    //暂无缴费有评价项
    __weak IBOutlet UILabel *_NoPayEvaluateLabel;//暂无缴费有评价
    __weak IBOutlet UILabel *_NOAllEvaluateTimeLabel;//评价总次数
    __weak IBOutlet UILabel *_NoUseEvaluateTimeLabel;//有效评价总次数;
    __weak IBOutlet UILabel *_NOSeeAllTimeLabel;//查看总次数;
    NSInteger _mark;//标记类型
    NSString *_selectDate;//标记选中的日期
}

+ (instancetype)ConfigCycleDetailHeaderViewWithComplete:(void (^)(NSInteger))Complete {

    return [[self alloc] initWithConfigCycleDetailHeaderViewWithComplete:Complete];
}

- (instancetype)initWithConfigCycleDetailHeaderViewWithComplete:(void (^)(NSInteger))Complete {
    
    self = [[NSBundle mainBundle] loadNibNamed:[HNSalesManCycleDetailView description] owner:nil options:nil][0];
    if (self) {
        
        [_CycleView addSubview:[self PieChart]];

    }
    return self;
}

- (CustomDayDatePicker *)datePicker {
    
    if (_datePicker == nil) {
        self.datePicker = [[CustomDayDatePicker alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth - 60, 140)];
        
    }
    
    
    return _datePicker;
}



/** 更新数据 */                              
- (void)setModel:(HNSalesManCycleDetailModel *)Model {
    
    _Model = Model;
    _Title.text = _Model.ResourcerModel.resourceName;
    _Name.text = [_Model.ResourcerModel.TitleArr componentsJoinedByString:@"、"];
    [_BeginTimeBtn.currentTitle isEqualToString:@"0000年0月"] ? [_BeginTimeBtn setTitle:[self getCurrentTime] forState:(UIControlStateNormal)]:nil;
    [_EndTimeBtn.currentTitle isEqualToString:@"0000年0月"] ? [_EndTimeBtn setTitle:[self getCurrentTime] forState:(UIControlStateNormal)]:nil;
    _CommentCount.text = [NSString stringWithFormat:@"%ld次",[_Model.threeCommentCount integerValue]];
    _SeeCount.text = [NSString stringWithFormat:@"%ld次",[_Model.threeCommentViewCount integerValue]];
    [[self PieChart] updateChartData:[self CycleDataWithModel:Model]];
    [[self PieChart] strokeChart];
    // 先移除所有的要素
    [_CategoryScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 创建所需的要素
    __block HNSalesManCyleDetailCategoryView *TempView = nil;
    [_Model.CategoryArr enumerateObjectsUsingBlock:^(HNSalesManCycleDetailCatgoryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 实例化
        HNSalesManCyleDetailCategoryView *View = [HNSalesManCyleDetailCategoryView ConfigCategoryViewWithModel:obj Complete:nil];
        [_CategoryScrollView addSubview:View];
        // 布局
        [View mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_CategoryScrollView.mas_top).offset(0);
            make.left.offset(kScreen_Width/3*idx);
            make.height.offset(_CategoryScrollView.height);
            make.width.offset(kScreen_Width/3);
        }];
        TempView = View;
    }];
    _CategoryScrollView.contentSize = CGSizeMake(TempView.frame.origin.x + TempView.frame.size.width, TempView.frame.size.height);
    
    // 业务详情
    _UnitLabel.text = [NSString stringWithFormat:@"￥%.2f",[_Model.totalSettleMoneyPay floatValue] + [_Model.totalSettleMoneyNotPay floatValue]];
    // 有效
    _PayEvaluateLabel.text = [NSString stringWithFormat:@"缴费评价:￥%.2f元",[_Model.totalSettleMoneyPay floatValue]];
    _AllEvaluateTimeLabel.text = [NSString stringWithFormat:@"评价总次数:%ld次",[_Model.threeCommentCountPay integerValue]];
    _UseEvaluateTimeLabel.text = [NSString stringWithFormat:@"有效评价总次数:%ld次",[_Model.validThreeCommentCountPay integerValue]];
    _SeeAllTimeLabel.text = [NSString stringWithFormat:@"查看总次数:%ld次",[_Model.totalViewCountPay integerValue]];
    // 无效
    _NoPayEvaluateLabel.text = [NSString stringWithFormat:@"暂无缴费有评价:￥%.2f",[_Model.totalSettleMoneyNotPay floatValue]];
    _NOAllEvaluateTimeLabel.text = [NSString stringWithFormat:@"评价总次数:%ld次",[_Model.threeCommentCountNotPay integerValue]];
    _NoUseEvaluateTimeLabel.text = [NSString stringWithFormat:@"有效评价总次数:%ld次",[_Model.validThreeCommentCountNotPay integerValue]];
    _NOSeeAllTimeLabel.text = [NSString stringWithFormat:@"查看总次数:%ld次",[_Model.totalViewCountNotPay integerValue]];}


#pragma mark - Func
/** 处理饼状图 */
- (NSArray *)CycleDataWithModel:(HNSalesManCycleDetailModel *)Model {
    
    NSMutableArray *Arr = [NSMutableArray array];
    [Model.resourcePieDatas enumerateObjectsUsingBlock:^(HNSalesManCycleDetailCycleModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIColor *Color = nil;
        if ([obj.courseType isEqualToString:@"普通课程"]) {
            
            Color = ColorRGB(102, 201, 186);
        } else if ([obj.courseType isEqualToString:@"加强课"]) {
            
            Color = ColorRGB(240, 152, 143);
        } else if ([obj.courseType isEqualToString:@"套餐课程"]) {
            
            Color = ColorRGB(245, 204, 111);
        } else {
            
            Color = nil;
        }
        CGFloat aaa = [obj.money floatValue]/[Model.totalMoney floatValue];
        NSString *Str = [NSString stringWithFormat:@"%.2f",aaa];
        aaa = [Str floatValue];
        aaa > 0 ? [Arr addObject:[PNPieChartDataItem dataItemWithValue:aaa  color:Color description:aaa < 0.2f ? @"":[NSString stringWithFormat:@"￥%@",[obj.money stringValue]]]]:nil;
    }];
    return [Arr copy];
}
//获取当地时间
- (NSString *)getCurrentTime {
    
    return [NSString yearMonthDay];
}

/** 判断结束时间是不要大于开始时间 */
- (BOOL)JudgeBigOrSmallWithBegin:(NSString *)Begin End:(NSString *)End {
    
    NSArray *BeginArr = [Begin componentsSeparatedByString:@"年"];
    NSString *BeginMouths = [[BeginArr lastObject] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSArray *EndArr = [End componentsSeparatedByString:@"年"];
    NSString *EndMouths = [[EndArr lastObject] stringByReplacingOccurrencesOfString:@"月" withString:@""];
    NSInteger BeginYear = [[BeginArr firstObject] integerValue];
    NSInteger BeginMouth = [BeginMouths integerValue];
    NSInteger EndYear = [[EndArr firstObject] integerValue];
    NSInteger EndMouth = [EndMouths integerValue];
    if (EndYear - BeginYear > 0) {
        
        return YES;
    }
    else if (EndYear - BeginYear == 0 && EndMouth - BeginMouth >= 0) {
        
        return YES;
    } else {
        
        return NO;
    }
}


/** 将2017年10月的格式转成2017-10 */
- (NSString *)MgrTimeStrFormatterWitStr:(NSString *)Str {
    
    Str = [Str stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
    Str = [Str stringByReplacingOccurrencesOfString:@"月" withString:@""];
    return Str;
}

#pragma mark - Action
/** 确定 */
- (IBAction)Sure:(UIButton *)sender {
    
    NSComparisonResult result = [_BeginTimeBtn.currentTitle compare:_EndTimeBtn.currentTitle];
    
    if (result != NSOrderedAscending) {
        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
    }else{
        
       self.RefreshDataForTime ? self.RefreshDataForTime([self MgrTimeStrFormatterWitStr:_BeginTimeBtn.currentTitle], [self MgrTimeStrFormatterWitStr:_EndTimeBtn.currentTitle]):nil;
        
    }
    
    
//    if (![self JudgeBigOrSmallWithBegin:_BeginTimeBtn.currentTitle End:_EndTimeBtn.currentTitle]) {
//
//        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
//    } else {
//        // 发起时间查询的请求
//        self.RefreshDataForTime ? self.RefreshDataForTime([self MgrTimeStrFormatterWitStr:_BeginTimeBtn.currentTitle], [self MgrTimeStrFormatterWitStr:_EndTimeBtn.currentTitle]):nil;
//    }
}
- (IBAction)Des:(UIButton *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"暂无缴费有评价：指的是学生导入到教学管理系统的第一个月内，老师对学生进行评价，家长查看这条评价。平台给与补贴，超过一个月没有补贴。后续在平台上缴费且有评价，补贴将计入到\"缴费评价\"" preferredStyle:(UIAlertControllerStyleAlert)];
    [alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:(UIAlertActionStyleDefault) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 时间选择
- (IBAction)ClickTimeAction:(UIButton *)sender {
    

    NSInteger tag = sender.tag;
    
    if (1100 == tag) {
            JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(30, kScreenHeight/2 - 100, kScreenWidth - 60, 200)];
            //alert.center = self.center;
            alert.delegate = self;
            [alert initwithtitle:@"开始时间" andcommitbtn:@"确定" andStr:@"0"];
            [alert addSubview:self.datePicker];
            [alert show];
        _mark = 1;
    }else{
            JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(30, kScreenHeight/2 -100, kScreenWidth - 60, 200)];
            alert.delegate = self;
            [alert initwithtitle:@"结束时间" andcommitbtn:@"确定" andStr:@"0"];
            [alert addSubview:self.datePicker];
            [alert show];
        _mark = 2;
    }
    
    

//    [[UIApplication sharedApplication].keyWindow addSubview:[[HNSalesManCycleDetailDateView alloc] initWithCurrentDate:sender.currentTitle Title:sender == _BeginTimeBtn ? @"开始时间":@"结束时间" Min:2000 Max:2050 Complete:^(NSString *DateStr) {
//        [sender setTitle:DateStr forState:(UIControlStateNormal)];
//    }]];
}

- (void)btnindex:(int)index :(int)tag{
    
    
    if (index == 2) {
        if (_mark == 1) {
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            [_BeginTimeBtn setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }else if (_mark == 2){
            
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            [_EndTimeBtn setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }
    }
    
}

#pragma mark - 饼图
- (PNPieChart *)PieChart {
    
    if (!_PieChart) {
        
        //For Pie Chart
        NSArray *items = @[[PNPieChartDataItem dataItemWithValue:50 color:PNRed description:@"孔帅哥"],
                           [PNPieChartDataItem dataItemWithValue:20 color:PNBlue description:@"其他人"],
                           [PNPieChartDataItem dataItemWithValue:30 color:PNGreen description:@"未知"],
                           ];
        
        PNPieChart *pieChart = [[PNPieChart alloc] initWithFrame:CGRectZero items:items];
        pieChart.descriptionTextColor = [UIColor whiteColor];
        pieChart.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:14.0];
        _PieChart = pieChart;
        [pieChart strokeChart];
    }
    return _PieChart;
}

- (void)layoutSubviews {
    
    [super layoutSubviews];

    _PieChart.frame = CGRectMake(0, 0, _CycleView.width/3*1.8, _CycleView.width/3*1.8);
    _PieChart.center = CGPointMake(_CycleView.width/2, _CycleView.height/2);
}
@end
